﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DevExpress.Web;
using Microsoft.Office.Interop.Excel;
using TheHeGeo.Util;
using TheHeGeoDao;
using DataTable = System.Data.DataTable;

namespace TheHeGeo.UserControl
{
    public partial class UcWarningManagement : System.Web.UI.UserControl
    {
        DataTable dt = new DataTable();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                LoadGrld();
                LoadSensorCbb();
                LoadTypeCbb();
            }
            else
            {
                grvData.DataSource = Session[SessionConst.SES_WARNING_VALUE];
                
            }
        }

        void LoadTypeCbb()
        {
            var cbb = grvData.Columns["Type"] as GridViewDataComboBoxColumn;
            if (cbb == null) return;
            cbb.PropertiesComboBox.Items.Clear();
            cbb.PropertiesComboBox.ValueType = typeof(string);
            cbb.PropertiesComboBox.Items.Add("Lớn hơn", "1");
            cbb.PropertiesComboBox.Items.Add("Nhỏ hơn", "0");
        }
        protected void LoadSensorCbb()
        {
            var cbb = grvData.Columns["MaSensor"] as GridViewDataComboBoxColumn;
            if (cbb == null) return;
            var us = ((SessionUser)Session[SessionConst.SES_USER]).NguoiSuDung.UserName;
            List<Sensor> dt = (from s in DaoHelper.Entities.Sensors
                        join t in DaoHelper.Entities.ThietBis on s.MaThietBi equals t.MaThietBi
                        join q in DaoHelper.Entities.PhanQuyenDuAns on t.MaDuAn equals q.MaDuAn
                        join a in DaoHelper.Entities.DuAns on q.MaDuAn equals a.MaDuAn
                        where (q.UserName == us && t.Status == 0)
                        select s).ToList();
           
            string user = ((SessionUser)(Session[SessionConst.SES_USER])).NguoiSuDung.UserName;
            cbb.PropertiesComboBox.Items.Clear();
            cbb.PropertiesComboBox.ValueType = typeof(string);
           
            foreach (var s in dt)
            {
                cbb.PropertiesComboBox.Items.Add(s.TenSensor, s.MaSensor);
            }
        }
        protected void LoadGrld()
        {
            var us = ((SessionUser)Session[SessionConst.SES_USER]).NguoiSuDung.UserName;
            var list = (from s in DaoHelper.Entities.Sensors
                join h in DaoHelper.Entities.GioiHanCanhBaos on s.MaSensor equals h.MaSensor
                join t in DaoHelper.Entities.ThietBis on s.MaThietBi equals t.MaThietBi
                join q in DaoHelper.Entities.PhanQuyenDuAns on t.MaDuAn equals q.MaDuAn
                join a in DaoHelper.Entities.DuAns on q.MaDuAn equals a.MaDuAn
                where (q.UserName == us&&t.Status==0)
                select new
                       {
                           h.Id,
                           h.MaSensor,
                           s.TenSensor,
                           h.GiaTri,
                           h.Type
                       }).ToList();
            
            dt.Columns.Add("Id", typeof (Int32));
            dt.Columns.Add("MaSensor", typeof(string));
            dt.Columns.Add("TenSensor", typeof(string));
            dt.Columns.Add("GiaTri", typeof(Double));
            dt.Columns.Add("Type", typeof(string));
            foreach (var s in list)
            {
                DataRow dr = dt.NewRow();
                dr["Id"] = s.Id;
                dr["MaSensor"] = s.MaSensor;
                dr["TenSensor"] = s.TenSensor;
                dr["GiaTri"] = s.GiaTri;
                dr["Type"] = s.Type;
                dt.Rows.Add(dr);
            }
            Session[SessionConst.SES_WARNING_VALUE] = dt;
            grvData.DataSource = dt;
            grvData.DataBind();

        }
        protected void grvData_RowDeleting(object sender, DevExpress.Web.Data.ASPxDataDeletingEventArgs e)
        {
            try
            {
                int id = Convert.ToInt32(e.Values["Id"]);
                var s = (from i in DaoHelper.Entities.GioiHanCanhBaos
                         where (i.Id == id)
                         select i).FirstOrDefault();
                if(s==null)
                    throw new ArgumentException("Delete không thành công!");
                DaoHelper.Entities.GioiHanCanhBaos.Remove(s);
                DaoHelper.Entities.SaveChanges();

            }
            catch (Exception)
            {

                throw new Exception("Delete không thành công. Vui lòng thử lại.");
            }
            e.Cancel = true;
            grvData.CancelEdit();
            LoadGrld();
        }

        protected void grvData_RowUpdating(object sender, DevExpress.Web.Data.ASPxDataUpdatingEventArgs e)
        {
            try
            {
                var dr = grvData.GetDataRow(grvData.EditingRowVisibleIndex);
                int id = Convert.ToInt32(dr["Id"].ToString());
                var s = (from i in DaoHelper.Entities.GioiHanCanhBaos
                         where (i.Id == id)
                         select i).FirstOrDefault();
                if (s == null)
                    throw new ArgumentException("Update không thành công!");
                s.GiaTri = Convert.ToDouble(e.NewValues["GiaTri"].ToString());
                s.Type = e.NewValues["Type"].ToString();
                DaoHelper.Entities.SaveChanges();
            }
            catch (ArgumentException)
            {
                throw;
            }
            catch (Exception)
            {
                throw new Exception("Update không thành công. Vui lòng thử lại.");
               
            }
            e.Cancel = true;
            grvData.CancelEdit();
            LoadGrld();
        }

        protected void grvData_RowInserting(object sender, DevExpress.Web.Data.ASPxDataInsertingEventArgs e)
        {
            try
            {
                grvData.DoRowValidation();
                string maSensor = e.NewValues["MaSensor"].ToString();
                Double giaTri = Convert.ToDouble(e.NewValues["GiaTri"].ToString());
                string type = e.NewValues["Type"].ToString();
                var warningValue = (from i in DaoHelper.Entities.GioiHanCanhBaos
                                    where (i.MaSensor == maSensor && i.GiaTri == giaTri && i.Type == type)
                                    select i).FirstOrDefault();
                if(warningValue!=null)
                    throw new ArgumentException("Giá trị cảnh báo của sensor đã tồn tại.");
                else
                {
                    var newValue = new GioiHanCanhBao();
                    newValue.MaSensor = maSensor;
                    newValue.GiaTri = giaTri;
                    newValue.Type = type;
                    DaoHelper.Entities.GioiHanCanhBaos.Add(newValue);
                    DaoHelper.Entities.SaveChanges();
                }
               
            }
            catch (ArgumentException)
            {
                throw;
            }
            catch (Exception)
            {

                throw new Exception("Thêm mới không thành công. Vui lòng thử lại.");
            }
            e.Cancel = true;
            grvData.CancelEdit();
            LoadGrld();
        }

        protected void grvData_StartRowEditing(object sender, DevExpress.Web.Data.ASPxStartRowEditingEventArgs e)
        {
            var c = grvData.Columns["MaSensor"] as GridViewDataColumn;
            if (c != null)
            {
                c.ReadOnly = true;
            }
        }
    }
}